package com.xmu.prcs.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;

import org.apache.struts2.json.annotations.JSON;

import com.xmu.prcs.action.bean.PlantInfoBean;
import com.xmu.prcs.action.bean.UserInfoBean;
import com.xmu.prcs.debugutil.DebugUtil;
import com.xmu.prcs.service.PlantInfoManager;
import com.xmu.prcs.service.SystemManager;
import com.xmu.prcs.service.UserManager;
import com.xmu.prcs.util.DictionaryUtil;

/**
 * 系统
 * @author frequent
 * @version 1.0,2012-3-20
 *
 */
@SuppressWarnings("serial")
public class SystemAction extends BaseAction{

	private SystemManager systemManager;
	
	private PlantInfoManager plantInfoManager;
	
	private UserManager userManager;
	/**
	 * 登录失败的详细信息
	 */
	private String loginExceptionMsg;
	
	/**
	 * 上传的文件
	 */
	private File upload;
	
	/**
	 * 上传的文件名
	 */
	private String uploadFileName;
	
	/**
	 * 上传的文件类型
	 */
	private String uploadContentType;
	
	/**
	 * 注册填入的用户信息
	 */
	private UserInfoBean user;
	
	/**
	 * 用户名
	 */
	private String userName;
	
	/**
	 * 用户密码
	 */
	private String password;
	
	/**
	 * 登录是否成功
	 */
	private boolean login;
	
	private int idUser;
	
	/**
	 * 判断是否被拦截
	 */
	private int isIntercepted;
	
	private List<PlantInfoBean> plants;

	@JSON(serialize=false)
	public SystemManager getSystemManager() {
		return systemManager;
	}

	public void setSystemManager(SystemManager systemManager) {
		this.systemManager = systemManager;
	}
	
	@JSON(serialize=false)
	public PlantInfoManager getPlantInfoManager() {
		return plantInfoManager;
	}

	public void setPlantInfoManager(PlantInfoManager plantInfoManager) {
		this.plantInfoManager = plantInfoManager;
	}

	@JSON(serialize=false)
	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	@JSON(serialize=false)
	public String getLoginExceptionMsg() {
		return loginExceptionMsg;
	}

	public void setLoginExceptionMsg(String loginExceptionMsg) {
		this.loginExceptionMsg = loginExceptionMsg;
	}

	@JSON(serialize=false)
	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	@JSON(serialize=false)
	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	@JSON(serialize=false)
	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	@JSON(serialize=false)
	public UserInfoBean getUser() {
		return user;
	}

	public void setUser(UserInfoBean user) {
		this.user = user;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isLogin() {
		return login;
	}

	public void setLogin(boolean login) {
		this.login = login;
	}

	public int getIdUser() {
		return idUser;
	}

	public void setIdUser(int idUser) {
		this.idUser = idUser;
	}

	public int getIsIntercepted() {
		return isIntercepted;
	}

	public void setIsIntercepted(int isIntercepted) {
		this.isIntercepted = isIntercepted;
	}

	public List<PlantInfoBean> getPlants() {
		return plants;
	}

	public void setPlants(List<PlantInfoBean> plants) {
		this.plants = plants;
	}

	/**
	 * 返回首页
	 * @return
	 */
	public String toIndex(){
		plants = plantInfoManager.getPlants4Index();
		return SUCCESS;
	}
	
	/**
	 * 定向到登录页面
	 * @return
	 */
	public String toLogin(){
		System.out.println("isIntercepted:" + isIntercepted );
		return SUCCESS;
	}
	
	/**
	 * 登录系统
	 * @return
	 */
	public String login(){
		idUser = userManager.getUserIdByUserName(userName);
		int role = userManager.getUserRoleById(idUser);
		this.getSession().setAttribute("userId", idUser);
		this.getSession().setAttribute("role", role);
		return SUCCESS;
	}
	
	/**
	 * 退出系统
	 * @return
	 */
	public String logout(){
		this.removeCookie(Integer.toString(idUser));
		this.getSession().removeAttribute("userId");
		this.getSession().removeAttribute("role");
		this.getSession().invalidate();
		return SUCCESS;
	}
	
	/**
	 * 注册前先查看注册信息
	 * @return
	 */
	public String seeRegisterInfo(){
		return SUCCESS;
	}
	
	/**
	 * 同意系统注册协议，进入注册
	 * @return
	 */
	public String toRegister(){
		return SUCCESS;
	}
	
	/**
	 * 注册
	 * @return
	 */
	public String register(){
		String fileName = uploadImage();//上传头像
		user.setPhoto(fileName);
		System.out.println("fileName:" + fileName);
		DebugUtil.printUserInfo(user);
		userManager.addUser(user);
		return SUCCESS;
	}
	
    /** 
     * 上传单个图片，返回图片存储文件名
     * @return 
     */  
    public String uploadImage(){  
    	if(upload == null || uploadFileName == null || uploadFileName.equals("")){
    		System.out.println("upload is empty....");
    		return DictionaryUtil.DEFAULT_PHOTO;
    	}
    	
    	try {
    		String fileName = this.createNewFileName();
    		String basePath = this.getRequest().getSession().getServletContext().getRealPath("") + "\\";
    		String storeFileName = basePath + fileName;
    		//防止文件名重复
    		int add = 1;
    		while(new File(storeFileName).exists()){
    			storeFileName += add;
    			add++;
    		}
			FileOutputStream fos = new FileOutputStream(storeFileName);
			InputStream is = new FileInputStream(upload);//页面传进来的文件
			byte[] buffer = new byte[8192]; //每次读写8K字节
			int count = 0;
			while((count = is.read(buffer)) > 0){
				fos.write(buffer, 0, count);
			}
			fos.close();
			is.close();
			return fileName;
		}catch(NullPointerException e){
			e.printStackTrace();
			return DictionaryUtil.DEFAULT_PHOTO;
		}
    	catch (FileNotFoundException e) {
			e.printStackTrace();
			return DictionaryUtil.DEFAULT_PHOTO;
		} catch (IOException e) {
			e.printStackTrace();
			return DictionaryUtil.DEFAULT_PHOTO;
		}
    }  
    
    /**
     * 得到新的文件名
     * @return
     */
    public String createNewFileName(){
    	Date date = new Date();
    	File filedir = new File(DictionaryUtil.UPLOAD_FILE_PATH);
    	if(!filedir.exists()){
    		filedir.mkdir();
    	}
    	String filename = DictionaryUtil.UPLOAD_FILE_PATH + "img";
    	filename += date.getTime();
    	System.out.println("uploadfilename:" + upload.getName());
    	System.out.println("name:" + uploadFileName);
    	System.out.println("type:" + uploadContentType);
    	//获得上传文件的后缀名
    	filename += uploadFileName.substring(uploadFileName.indexOf("."));
    	return filename;
    }

    /**
     * 跳转到修改密码页面
     * @return
     */
    public String toModifyPwd(){
    	return SUCCESS;
    }
    
    /**
     * 修改密码
     * @return
     */
    public String modifyPwd(){
    	
    	return SUCCESS;
    }
    
    /**
     * 登录则新建cookie
     * @param username
     */
	public void addCookie(String userId){
		Cookie cookie =  new  Cookie("USERID",userId);    
		cookie.setMaxAge(-1); 
		cookie.setPath("/");
		this.getResponse().addCookie(cookie);    

	}
	
	/**
	 * 退出注销cookie
	 * @param username
	 */
	public void removeCookie(String username){
		Cookie cookie =  new  Cookie("USERNAME","");    
		cookie.setMaxAge(0); 
		cookie.setPath("/");
		this.getResponse().addCookie(cookie);    

	}
}
